package com.woorigil.social.worker;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.woorigil.social.domain.ApplicationService;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.deal.Deal;
import com.woorigil.social.domain.deal.DealDao;
import com.woorigil.social.domain.deal.DealListDocument;
import com.woorigil.social.domain.deal.ManageStatus;
import com.woorigil.social.domain.deal.repository.DealListDao;
import com.woorigil.social.domain.history.WorkHistory;
import com.woorigil.social.domain.history.WorkHistoryDao;
import com.woorigil.social.domain.point.DealPointDao;
import com.woorigil.social.parser.Parser;
import com.woorigil.social.parser.wemakeprice.WemakepriceXmlParser;
import com.woorigil.social.worker.ordering.DealOrderingManager;
import com.woorigil.social.worker.task.DealLoadProcessor;
import com.woorigil.social.worker.task.DealSaveProcessor;

@Component
public class AllDealLoadWorker {
	private static Logger log = LoggerFactory.getLogger(AllDealLoadWorker.class);
	
	public static final String WORK_NAME = "DEAL_LOAD";
	@Autowired List<Parser> parsers;
	@Autowired DealDao dealDao;
	@Autowired DealListDao dealListDao;
	@Autowired DealPointDao dealPointDao;
	@Autowired WorkHistoryDao workHistoryDao;
	@Autowired ApplicationService applicationInitService;
	@Autowired DealLoadProcessor dealLoadProcessor;
	@Autowired DealSaveProcessor dealSaveProcessor;
	@Autowired DealOrderingManager dealOrderingManager;

	public void execute() throws Exception {
		if (parsers == null) {
			return;
		}

		for (Parser parser : parsers) {
			log.info("parser start : " + parser.getProviderCode());

			try {
				DealListDocument dealListDocument = dealLoadProcessor.process(parser);
				preProcess(parser.getProviderCode());
				mainProcess(dealListDocument);
				postProcess(parser.getProviderCode());
			} catch (Exception e) {
				log.error("parse error : " + parser.getProviderCode(), e);
			}
		}

		WemakepriceXmlParser.extraDeals  = null;
		dealOrderingManager.manage();
		workHistoryDao.insert(new WorkHistory(WORK_NAME, new Date()));
		applicationInitService.settingInfo();
	}

	private void postProcess(ProviderCode providerCode) {
		dealDao.deleteByManageStatus(providerCode, ManageStatus.D);
		dealPointDao.deleteByManageStatus(providerCode, ManageStatus.D);
	}

	private void mainProcess(DealListDocument dealListDocument) {
		for (Deal newDeal : dealListDocument.getDeals()) {
			dealSaveProcessor.process(newDeal);
		}
	}

	private void preProcess(ProviderCode providerCode) {
		dealDao.updateStatus(providerCode, ManageStatus.D);
		dealPointDao.updateStatus(providerCode, ManageStatus.D);
	}
}
